
'''A collection of functions that convert Python objects to json and back.'''

import datetime
import simplejson

def datetime_from_plurk_string(s):
  return datetime.datetime(2000,1,1).strptime(s, '%a, %d %b %Y %H:%M:%S %Z')

def conv_datetime(v):
  return v.isoformat()

def conv_date(v):
  return v.strftime('%Y-%m-%d')

def identity(v):
  return v

def conv_bool(v):
  return simplejson.dumps(v)

def conv_dict_values(dic, **func_table):
  result = {}
  for k, v in dic.iteritems():
    if func_table.has_key(k): result[k] = func_table[k](v)
    else: result[k] = conv_autodetect(v)
  return result

def conv_autodetect(v):
  return conv_bool(v) if type(v) == bool else \
         conv_datetime(v) if type(v) == datetime.datetime else \
         conv_dict_values(v) if type(v) == dict else \
         v
